package com.lc.command;

import com.lc.protocol.DeviceError;

import org.json.JSONObject;
import java.lang.reflect.Method;

/**
 * Created by zhyioo on 2017/8/8.
 */

public class ReflecterCommand implements ICommand {

    protected Object _obj = null;
    protected Method _method = null;

    public ReflecterCommand() {}

    public ReflecterCommand(Object obj, String methodName) {
        Make(obj, methodName);
    }

    public boolean Make(Object obj, String methodName) {
        try {
            _obj = obj;
            _method = null;

            if(_obj != null) {
                Class<?> classModule = Class.forName(_obj.getClass().getName());
                _method = classModule.getMethod(methodName, JSONObject.class, JSONObject.class);
            }
            return IsValid();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean IsValid() {
        return _obj != null && _method != null;
    }

    @Override
    public boolean Run(JSONObject arg, JSONObject rlt) {
        if(!IsValid()) {
            return false;
        }
        boolean bOK = false;
        Object retObj = null;
        try {
            retObj = _method.invoke(_obj, arg, rlt);
            bOK = Boolean.parseBoolean(retObj.toString());
            return bOK;
        } catch (Exception e) {
            e.printStackTrace();
            CommandActuator.LogErr(rlt, DeviceError.OperatorStatusErr, e.toString());
        }
        return false;
    }
}
